package org.example.myframework.frame.demo.service.temp;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 多线程测试类
 */
public class ExecutorTestService {

    public static final int THREAD_POOL_NUM = 3;

    public static void main(String[] args) {
        // 创建多线程，指定线程数

        // 获取线程执行后返回结果
        // getExecutorResultBlock();
        getExecutorResultAsync();
        System.out.println("-------------main continue");


    }

    /**
     * 异步获取返回结果的方案
     */
    private static void getExecutorResultAsync() {

        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            // 模拟耗时任务
            try {
                System.out.println("sleeping------");
                // 在休眠的时候，由于是异步的执行，所以在苏醒之前主方法已经结束了，因此没有返回结果。
                Thread.sleep(2000);
                System.out.println("weak------");

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return 42;
        });
        integerCompletableFuture
                .thenAccept(result -> System.out.println("Result: " + result)); // 非阻塞处理结果
        System.out.println("-------------method continue");

    }

    /**
     * 阻塞主线程获取返回结果的方案
     */
    private static void getExecutorResultBlock() {
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_NUM);

        Future<String> future = executorService.submit(() -> {
            // 执行耗时任务
            try {
                Thread.sleep(2000);
                return "sleep done";
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        String result = "";
        try {
            // 获取多线程的返回结果
            result = future.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("result: " + result);
        }
        executorService.shutdown();
    }

}
